import VueRouter from 'vue-router'
import Vue from 'vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Layout from '../views/Layout.vue'
import MessageList from '../views/MessageList.vue'
import UserDetail from '../views/UserDetail.vue'
import FriendDetail from '../views/FriendDetail.vue'
import GroupDetail from '../views/GroupDetail.vue'
import Search from '../views/Search.vue'


Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component:Login
  },

  {
    path:'/register',
    name:"Register",
    component:Register
  },
  {
    path:'/',
    name:"layout",
    component:Layout,
    children:[
      {
        path:'/userDetail',
        name:"userDetail",
        component:UserDetail
      },
      {
        path:'/friendDetail',
        name:"friendDetail",
        component:FriendDetail
      },
      {
        path:'/groupDetail',
        name:"groupDetail",
        component:GroupDetail
      },
      {
        path:'/search',
        name:"search",
        component:Search
      },
      {
        path:"/messageList",
        name:"messageList",
        component:MessageList
      }
    ]
  },
  
]

const router = new VueRouter({
  //mode默认值是hash，当设置为history时，URL更加简洁，但部署到后台时，需要额外的配置。
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//路由守卫
router.beforeEach((to,from,next) => {
  if(to.path == '/login'||to.path=='/register'){
    next();
  }else{
    if(localStorage.getItem("token")){
      next();
    }else{
      next("/login")
    }
  }
})

//防止element-ui路由跳转报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
export default router
